﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OnlineOrder.UI.管理员窗口
{
    public partial class SocketService : Form
    {
        public SocketService()
        {
            InitializeComponent();
            //如果子线程需要使用主线程中创建的对象和控件，最好在主线程中体现进行检查取消
            CheckForIllegalCrossThreadCalls=false;
        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void SocketService_Leave(object sender, EventArgs e)
        {

        }

        private void SocketService_Load(object sender, EventArgs e)
        {
            var ip=IPAddress.Any.ToString();
            this.txt_IpAddress.Text = ip;
            var port = 9999;
            this.txt_Port.Text = port.ToString();
        }
        //创建字典用来记录服务端和客户端之间的连接（线程问题）
        Dictionary<string, System.Net.Sockets.Socket> clientList = new Dictionary<string, System.Net.Sockets.Socket>();

        private void btn_Create_Click(object sender, EventArgs e)
        {
            System.Threading.Thread myServer = new System.Threading.Thread(MySocket);
            myServer.IsBackground=true;
            myServer.Start();
        }
        //连接的方法
        public void MySocket()
        {
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            IPAddress iP=IPAddress.Parse(this.txt_IpAddress.Text);
            IPEndPoint endPoint=new IPEndPoint(iP,int.Parse(this.txt_Port.Text));
            server.Bind(endPoint);
            server.Listen(20);
            this.txt_MesssageBox.AppendText("服务器已经成功开启!\r\n");
            while(true)
            {
                Socket connecClient =server.Accept();
                if(connecClient != null)
                {
                    string infor=connecClient.RemoteEndPoint.ToString();
                    clientList.Add(infor,connecClient);
                    this.txt_MesssageBox.AppendText("用户" + "加入服务器!\r\n");
                    string msg = $"用户已经成功进入聊天室!";
                    SendMsg(msg);
                    Thread threadClient = new Thread(ReciveMsg);
                    threadClient.IsBackground=true;
                    threadClient.Start(connecClient);
                }
            }
        }

        public void ReciveMsg(object o)
        {
           Socket client=o as Socket;
            while (true)
            {
                try
                {
                    byte[] arrMsg = new byte[1024 * 1024];
                    int len = client.Receive(arrMsg);
                    if(len > 0)
                    {
                        string recMsg = Encoding.UTF8.GetString(arrMsg, 0, len);
                        IPEndPoint endPoint = client.RemoteEndPoint as IPEndPoint;
                        this.txt_MesssageBox.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\r\n用户:{recMsg} \r\n");
                        //SendMsg($"[{endPoint.Port.ToString()}]{recMsg}");
                    }
                }
                catch (Exception )
                {
                    client.Close();
                    clientList.Remove(client.RemoteEndPoint.ToString());
                }
            }
        }

        public void SendMsg(string msg)
        {
            foreach(var item in clientList)
            {
                byte[] arrMsg=Encoding.UTF8.GetBytes(msg);
                item.Value.Send(arrMsg);
            }
            this.txt_MesssageBox.AppendText($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}\r\n管理员：{msg} \r\n");
        }

        private void btn_Send_Click(object sender, EventArgs e)
        {
            if (this.txtSendBox.Text != "")
            {
                SendMsg(this.txtSendBox.Text);
                this.txtSendBox.Text = " ";
            }
        }


    }
}
